//
//  AppDelegate.m
//  nsj_iOS
//
//  Created by apple on 2016/12/7.
//  Copyright © 2016年 GCZ. All rights reserved.
//

#import "AppDelegate.h"
#import "CZBaseTabBarController.h"
#import "CZUserLoginViewController.h"
#import <KSCrash/KSCrashInstallationStandard.h>
#import <FBRetainCycleDetector/FBRetainCycleDetector.h>
// 引入JPush功能所需头文件
#import "JPUSHService.h"

// iOS10注册APNs所需头文件
#ifdef NSFoundationVersionNumber_iOS_9_x_Max
#import <UserNotifications/UserNotifications.h>
#endif

/*友盟第三方登录*/
#import <UMSocialCore/UMSocialCore.h>


@interface AppDelegate () <JPUSHRegisterDelegate>

@end

@implementation AppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    [NSThread sleepForTimeInterval:2.0];

    
    [SVProgressHUD setMinimumDismissTimeInterval:1.5];
    [SVProgressHUD setDefaultMaskType:(SVProgressHUDMaskTypeClear)];
    
    self.window = [[UIWindow alloc]initWithFrame:[UIScreen mainScreen].bounds];
    CZBaseTabBarController *baseTabBarController = [[CZBaseTabBarController alloc] init];
    [self.window setRootViewController:baseTabBarController];
    [self.window makeKeyAndVisible];
    
    /*Bug 检测*/
    KSCrashInstallationStandard* installation = [KSCrashInstallationStandard sharedInstance];
    installation.url = [NSURL URLWithString:@"https://collector.bughd.com/kscrash?key=5394429876ffbcdabafc78392948f1b2"];
    [installation install];
    [installation sendAllReportsWithCompletion:nil];
    
    /*设置第三方登录*/
    [self setUMSocial];
    /*设置推送*/
    [self setPushConfigurationWith:launchOptions];
    /*设置唯一标示*/
    if (![CZUUIDManager readUUID]) {
        [CZUUIDManager saveUUID: [UIDevice currentDevice].identifierForVendor.UUIDString];
    }
//    [JPUSHService setLogOFF];
    application.applicationIconBadgeNumber = 0;
    
    /*美拍*/
//    [MPShareSDK registerApp:@"1089867623"];
    
    /*设置自动更新*/
    [self checkUpdateWithAPPID:@"1192191057"];
//    [self checkUpdateWithAPPID:@"1025630946"];
    
    return YES;
    
}
- (void)setPushConfigurationWith:(NSDictionary *)launchOptions {
    if ([[UIDevice currentDevice].systemVersion floatValue] >= 10.0) {
        //iOS10以上
        JPUSHRegisterEntity * entity = [[JPUSHRegisterEntity alloc] init];
        entity.types = UNAuthorizationOptionAlert|UNAuthorizationOptionBadge|UNAuthorizationOptionSound;
        [JPUSHService registerForRemoteNotificationConfig:entity delegate:self];
    }else if ([[UIDevice currentDevice].systemVersion floatValue] >= 8.0) {
        //iOS8以上可以添加自定义categories
        [JPUSHService registerForRemoteNotificationTypes:(UIUserNotificationTypeBadge | UIUserNotificationTypeSound | UIUserNotificationTypeAlert) categories:nil];
    }
    
    BOOL isProduction = YES;// NO为开发环境，YES为生产环境
    //Required(2.1.5版本的SDK新增的注册方法，改成可上报IDFA，如果没有使用IDFA直接传nil
    
    [JPUSHService setupWithOption:launchOptions appKey:@"8503e0430b83bccbf108ee86"
                          channel:nil
                 apsForProduction:isProduction
            advertisingIdentifier:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(networkDidLogin:)
                                                 name:kJPFNetworkDidLoginNotification
                                               object:nil];
}
- (void)networkDidLogin:(NSNotification *)notification {
    
    DLog(@"jpush---已登录 registrationID = %@", [JPUSHService registrationID]);
    if ([JPUSHService registrationID]) {
        [[NSUserDefaults standardUserDefaults] setObject:[JPUSHService registrationID] forKey:mRegisterId];
    }
}


- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
    [JPUSHService registerDeviceToken:deviceToken];
}
- (void)application:(UIApplication *)application
didFailToRegisterForRemoteNotificationsWithError:(NSError *)error{
    DLog(@"did Fail To Register For Remote Notifications With Error: %@", error);
}
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {
    
    [JPUSHService handleRemoteNotification:userInfo];
    NSLog(@"iOS7及以上系统，收到通知:%@", [self logDic:userInfo]);
    completionHandler(UIBackgroundFetchResultNewData);
    
}

-(NSString *)logDic:(NSDictionary *)dic {
    if (![dic count]) {
        return nil;
    }
    NSString *tempStr1 =
    [[dic description] stringByReplacingOccurrencesOfString:@"\\u"
                                                 withString:@"\\U"];
    NSString *tempStr2 =
    [tempStr1 stringByReplacingOccurrencesOfString:@"\"" withString:@"\\\""];
    NSString *tempStr3 =
    [[@"\"" stringByAppendingString:tempStr2] stringByAppendingString:@"\""];
    NSData *tempData = [tempStr3 dataUsingEncoding:NSUTF8StringEncoding];
    NSString *str = [NSPropertyListSerialization propertyListWithData:tempData options:NSPropertyListImmutable format:NULL error:NULL];
    return str;
}
#ifdef NSFoundationVersionNumber_iOS_9_x_Max
#pragma mark- JPUSHRegisterDelegate
-(void)jpushNotificationCenter:(UNUserNotificationCenter *)center
       willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(NSInteger))completionHandler {
    
    NSDictionary * userInfo = notification.request.content.userInfo;
    UNNotificationRequest *request = notification.request; // 收到推送的请求
    UNNotificationContent *content = request.content; // 收到推送的消息内容
    NSNumber *badge = content.badge;  // 推送消息的角标
    NSString *body = content.body;    // 推送消息体
    UNNotificationSound *sound = content.sound;  // 推送消息的声音
    NSString *subtitle = content.subtitle;  // 推送消息的副标题
    NSString *title = content.title;  // 推送消息的标题
    
    
    if([notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
        [JPUSHService handleRemoteNotification:userInfo];
        NSLog(@"iOS10 前台收到远程通知:%@", [self logDic:userInfo]);
    }
    // 需要执行这个方法，选择是否提醒用户，有Badge、Sound、Alert三种类型可以设置
    completionHandler(UNNotificationPresentationOptionBadge|UNNotificationPresentationOptionSound|UNNotificationPresentationOptionAlert);
}
//
-(void)jpushNotificationCenter:(UNUserNotificationCenter *)center
didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)())completionHandler {
    NSDictionary * userInfo = response.notification.request.content.userInfo;
    UNNotificationRequest *request = response.notification.request; // 收到推送的请求
    UNNotificationContent *content = request.content; // 收到推送的消息内容
    NSNumber *badge = content.badge;  // 推送消息的角标
    NSString *body = content.body;    // 推送消息体
    UNNotificationSound *sound = content.sound;  // 推送消息的声音
    NSString *subtitle = content.subtitle;  // 推送消息的副标题
    NSString *title = content.title;  // 推送消息的标题
    if([response.notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {        
//        [[UIApplication sharedApplication] setApplicationIconBadgeNumber:content.badge.integerValue + 1];
        DLog(@"iOS10 收到远程通知:%@", [self logDic:userInfo]);
    }
    completionHandler();  // 系统要求执行这个方法
}
#endif
/*******************************以上推送*********************************/


// 第三方登录
- (void)setUMSocial {
    /*友盟*/
    [[UMSocialManager defaultManager] setUmSocialAppkey:@"586dfaca9f06fd14620000f7"];
    
    /*QQ登录*/
    [[UMSocialManager defaultManager] setPlaform:UMSocialPlatformType_QQ appKey:@"1105910562"  appSecret:nil redirectURL:@"http://mobile.umeng.com/social"];
    /*微信登录*/
    [[UMSocialManager defaultManager] setPlaform:UMSocialPlatformType_WechatSession appKey:@"wxec7d33cf80d777a8" appSecret:@"6bb55cdaa41d8c02812fcf5229deda86" redirectURL:@"http://mobile.umeng.com/social"];
}

#pragma mark -  支付等第三方回调
- (BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary<UIApplicationOpenURLOptionsKey,id> *)options {
//    BOOL result = [[UMSocialManager defaultManager] handleOpenURL:url];
    if ([Pingpp handleOpenURL:url withCompletion:nil]) {
        return YES;
    } else if([[UMSocialManager defaultManager] handleOpenURL:url]){
        [SVProgressHUD showWithStatus:@"正在登录..."];
        return YES;
    }
    return YES;
}

- (void)shareToMeipaiDidSucceed:(BOOL)success {
    if (success) {
        [SVProgressHUD showSuccessWithStatus:@"分享成功 请到美拍查看"];
    } else {
        [SVProgressHUD showErrorWithStatus:@"分享失败"];
    }
    DLog(@"%i",success);
}

- (void)checkUpdateWithAPPID:(NSString *)APPID {
    
    NSString* urlString = [NSString stringWithFormat:@"https://itunes.apple.com/lookup?id=%@",APPID];
    
    // 创建任务管理
    AFHTTPSessionManager *sessionManger = [AFHTTPSessionManager manager];
    
    [sessionManger POST:urlString parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        long resultCount = [[responseObject objectForKey:@"resultCount"] integerValue];
        if (resultCount == 1) {
            NSArray *resultArray = [responseObject objectForKey:@"results"];
            NSDictionary *resultDict = [resultArray objectAtIndex:0];
            NSString *newVersion = [resultDict objectForKey:@"version"];
            NSString *value1=[newVersion stringByReplacingOccurrencesOfString:@"." withString:@""];
            NSString *currentVersion = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"];
            NSString *value2=[currentVersion stringByReplacingOccurrencesOfString:@"." withString:@""];
            
            if ([value1 doubleValue] > [value2 doubleValue]) {
                NSString *msg = [NSString stringWithFormat:@"最新版本为%@,是否更新？",newVersion];
                UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"提示" message:msg preferredStyle:(UIAlertControllerStyleAlert)];
                UIAlertAction *confirmAlert = [UIAlertAction actionWithTitle:@"更新" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
                    NSString *newVersionURlString = [[resultDict objectForKey:@"trackViewUrl"] copy];
                    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:newVersionURlString]];
                    [alertController dismissViewControllerAnimated:YES completion:nil];
                }];
                UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"取消" style:(UIAlertActionStyleCancel) handler:^(UIAlertAction * _Nonnull action) {
                    
                    [alertController dismissViewControllerAnimated:YES completion:nil];
                }];
                [alertController addAction:confirmAlert];
                [alertController addAction:cancel];
                [self.window.rootViewController presentViewController:alertController animated:YES completion:nil];
                
            }
        }

    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
    }];
    
    
//    [GCZAFNetWorking POST:urlString params:nil success:^(id response) {
//            } failure:^(NSURLSessionDataTask *operation, NSError *error) {
//        NSLog(@"########网络错误");
//    }];
}



- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}


- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}


- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}


- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}


- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}


@end
